package com.bungarus.group.config;

import com.bungarus.group.auth.HttpHeaderAuthTokenSecurityConfigurer;
import com.bungarus.group.auth.SessionTokenAuthProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

//import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

/**
 * Created by tang on 2019/7/4.
 */
@Configuration
@PropertySource("application.properties")
@EnableWebSecurity
public class GlobalAuthWebConfigAdapter extends WebSecurityConfigurerAdapter {

    @Value("${token.tint}")
    String key;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/gs/v1.0/login/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .logout().disable()
                .apply(headerAuthToken(authenticationManagerBean()));
    }

    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(sessionTokenAuthProvider());
    }

    @Bean
    public AuthenticationProvider sessionTokenAuthProvider() {
        return new SessionTokenAuthProvider(key);
    }

    private HttpHeaderAuthTokenSecurityConfigurer headerAuthToken(AuthenticationManager authenticationManager) {
        return new HttpHeaderAuthTokenSecurityConfigurer(authenticationManager, key);
    }
}
